package bank.savingspassbook.service;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;

import bank.exception.DepositException;
import bank.exception.NotFoundAccountException;
import bank.exception.WithdrawalException;
import bank.savingspassbook.dao.SavingsPassbookDAO;
import bank.savingspassbook.vo.SavingsPassbook;

public class SavingspassbookService {
	private SavingsPassbookDAO dao = SavingsPassbookDAO.getInstance();
	private static SavingspassbookService service = new SavingspassbookService();
	private SavingspassbookService() {	}
	public static SavingspassbookService getInstance(){
		return service;
	}
	public void depositMoney(String accountNumber, int money) throws Exception {
		int count = dao.updateSavingsPassbookById(accountNumber, money);
		if(count == 1){
			System.out.println(accountNumber + "계좌에 정상 입금되었습니다.");
		} else {
			throw new DepositException(accountNumber + "계좌에서 입금을 실패하였습니다.");
		}
	}
	
	public void withdrawal(String accountNumber, int money) throws Exception {
		SavingsPassbook savingsPassbook = dao.selectSavingsPassbookByAccountNo(accountNumber);
		if(savingsPassbook == null){
			throw new NotFoundAccountException(accountNumber + "계좌가 존재하지 않습니다.");
		}
		int year = Integer.parseInt(savingsPassbook.getExpiryDate().split("-")[0]);
		int month = Integer.parseInt(savingsPassbook.getExpiryDate().split("-")[1]);
		int day = Integer.parseInt(savingsPassbook.getExpiryDate().split("-")[2]);
		GregorianCalendar expiryDate = new GregorianCalendar(year, month, day);
		GregorianCalendar today = new GregorianCalendar();
		if(today.before(expiryDate)){
			SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
			throw new WithdrawalException(accountNumber + "계좌의 만기일이 지나지 않았습니다.\n" + accountNumber + "계좌의 만기일 : " + sdf.format(expiryDate.getTime()));
		}
		
		if(savingsPassbook.getMoney() < money){
			throw new WithdrawalException(accountNumber + "계좌에 잔액이 부족합니다.\n" + "잔액 : " + savingsPassbook.getMoney() + ", 출금액 : " + money);
		}
		
		int count = dao.updateSavingsPassbookById(accountNumber, (-money));
		
		if(count == 1){
			System.out.println(accountNumber + "계좌에 정상 출금되었습니다.");
		} else {
			throw new WithdrawalException(accountNumber + "계좌에서 출금을 실패하였습니다.");
		}
	}
	
	public SavingsPassbook findSavingsPassbookByAccountNo(String accountNumber) throws Exception{
		return dao.selectSavingsPassbookByAccountNo(accountNumber);
	}
	
	public ArrayList<SavingsPassbook> findSavingsPassbookList() throws Exception{
		return dao.selectSavingsPassbookList();
	}
	
	public void interestAccrues() throws SQLException {
		dao.updateSavingsPassbookByInterest();
	}
}
